import { readJsonSync, existsSync } from 'fs-extra';
import path from 'path';
//import { merge } from 'lodash';

import { EnvironmentType } from '../environment';

function mergeConfig(fromConfig: any, toConfig: any) {
    let newConfig = { ...fromConfig };

    if (!!fromConfig && !!toConfig) {
        // #TODO　check config depth
        // override all match config without check it's depth
        Object.keys(toConfig)?.forEach((toKey) => {
            const toConfigValue = toConfig?.[toKey];

            if (/Object]$/.test(Object.prototype.toString.call(toConfigValue))) {
                // is object call merge again
                newConfig[toKey] = mergeConfig(newConfig?.[toKey], toConfigValue);
            } else {
                // other type, replace directly
                newConfig[toKey] = toConfigValue;
            }
        });

        // newConfig = merge(fromConfig, toConfig);
    }

    return newConfig;
}

function getConfig<T = any>(name: string, specificPath: string, env: EnvironmentType) {
    try {
        const baseFile = readJsonSync(path.join(specificPath, name));
        const commonConfig = baseFile?.default ?? baseFile;
        const additionalFilePath = path.join(specificPath, env, name);

        if (additionalFilePath?.length > 0 && existsSync(additionalFilePath)) {
            const additionalFile = readJsonSync(additionalFilePath);

            const additionalConfig = additionalFile?.default ?? additionalFile;

            return mergeConfig(commonConfig, additionalConfig) as T;
        }

        return commonConfig as T;
    } catch (err) {
        console.log('get config:', name, 'Error:', err);
        return {} as T;
    }
}

export { getConfig };
